#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#define N 1000000000

pthread_mutex_t b2access, m1, m2;
double pi;
double a1 = 1.0, b1 = 0.707106781186547524400844362, b2, t = 0.25, a2;

void *squareRoot(void *args) {
  int i;
  for (i=0; i<N; i++) {
    pthread_mutex_lock(&m1);
    b2 = sqrt(a1*b1);
    a1 = a2;
    b1 = b2;
    pthread_mutex_unlock(&m2);
  }
  pthread_exit(NULL);
}

void *gaussLegendre(void *args) {
  long long p = 1;
  int i;
  for(i=0; i<N; i++) {
    pthread_mutex_lock(&m2);
    a2 = (a1 + b1)/2.0;
    t = t - p*(a1 - a2)*(a1 - a2);
    if (i < 1023)
    p = p << 1;
    pthread_mutex_unlock(&m1);
  }
  pi = (a2 + b2)*(a2 + b2)/(4.0*t);
  pthread_exit(NULL);
}

int main() {
  pthread_mutex_init(&b2access, NULL);
  pthread_mutex_init(&m1, NULL);
  pthread_mutex_init(&m2, NULL);
  pthread_mutex_lock(&m1);
  pthread_t t1, t2;
  pthread_create(&t1, NULL, gaussLegendre, NULL);
  pthread_create(&t2, NULL, squareRoot, NULL);
  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  printf("%.6lf\n", pi);
  return 0;
}
